package thread2;

/**
 * Created with IntelliJ IDEA.
 * Description:死锁场景
 * User: bjc
 * Date: 2025-08-18
 * Time: 22:07
 */
public class ThreadDemo5 {
    public static void main(String[] args) throws InterruptedException {
        //创建一个对象
        Object A = new Object();
        Object B = new Object();

        //创建两个线程
        Thread t1 = new Thread(() -> {
            synchronized (A) {
                System.out.println("线程1拿到锁A");
                //为了让线程2有时间拿到锁B
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //在持有锁A的前提下，去获取锁B
                synchronized (B) {
                    System.out.println("线程1持有两把锁");
                }
            }

        });
        Thread t2 = new Thread(() -> {
            synchronized (B) {
                System.out.println("线程2获取锁B");
                //为了让线程1有时间拿到锁A
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //在持有锁B的前提下，去获取锁A
                synchronized (A) {
                    System.out.println("线程2持有两把锁");
                }
            }

        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}
